package com.wuwei.aliocr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wuwei.aliocr.domain.*;
import com.wuwei.aliocr.exception.TiKuException;
import com.wuwei.aliocr.result.Result;
import com.wuwei.aliocr.service.TikuService;
import com.wuwei.aliocr.utils.CommonUtils;
import com.wuwei.aliocr.utils.WxUtils;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class TikuServiceImpl implements TikuService {

    @Autowired
    private WxUtils wxUtils;

    @Value("${myWx.env}")
    private String env;


    /**
     * 更新数据库的数据
     * @param query
     * @return
     * @throws Exception
     */
    private Result wxUtils(String query) throws Exception {
        Map<Object, Object> bodys = new HashMap<>();
        bodys.put("env",env);
        System.out.println(query);
        bodys.put("query",query);
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databaseupdate";
        Result result = wxUtils.getSqlFromWxPost(bodys, host, path);
        return  result;
    }

    /**
     * 下载数据库文件
     * @param
     */
    public String download(Integer jobId) throws Exception {
        Map<String, Object> bodys = new HashMap<>();
        bodys.put("env",env);
        bodys.put("job_id",jobId);
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databasemigratequeryinfo";
        Result result = wxUtils.getSqlFromWxPost(bodys, host, path);
        Object data = result.getData();
        String s = data.toString();
        JSONObject jsonObject = JSONObject.parseObject(s);
        String file_url = (String) jsonObject.get("file_url");
        return file_url;
    }



    /**
     * 备份对应集合的方法
     */
    public Integer backup(String collection) throws Exception {
        Map<String, Object> bodys = new HashMap<>();
        bodys.put("env",env);
        bodys.put("file_type",1);
        bodys.put("file_path","test_export.txt");
        bodys.put("query","db.collection(\"shuati\").get()");
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databasemigrateexport";
        Result result = wxUtils.getSqlFromWxPost(bodys,host,path);
        Object data = result.getData();
        String s = data.toString();
        JSONObject jsonObject = JSONObject.parseObject(s);
        int jobId = jsonObject.getIntValue("job_id");
        return jobId;
    }

    @Override
    public String backupSql(String collection) throws Exception {
        //导出当前所在的数据库,以作备份
        Integer jobId = this.backup(collection);
        String download;
        while (true){
            download = this.download(jobId);
            if (!"".equals(download)){
                break;
            }
        }
        return download;
    }

    /**
     * 给题目标题，通过标题找出该题目的题号
     * @param question
     * @return
     */
    @Override
    public Integer findTihao(String question) {
        String questionIndex = "";
        String regex = "^[0-9]*$"; //0-9正整数的正则表达式
        // 对每个item的question遍历
        for (int i = 0; i < question.length(); i++) {
            char c = question.charAt(i);
            if (String.valueOf(c).matches(regex)) { //如果找到的字符是数字
                questionIndex += c;
            } else {
                break;
            }
        }
        return Integer.valueOf(questionIndex);
    }

    /**
     * 管理员用于删除用户反馈的数据的方法
     * @param account
     * @param time
     */
    @SneakyThrows
    @Override
    public void remove(String account, Long time) {
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databasedelete";
        Map<String, Object> bodys = new HashMap<>();
        bodys.put("env",env);
        String  query = "db.collection(\"feedBack\").where({\"account\":\""+account+"\",\"time\":"+time+"}).remove()";
        bodys.put("query",query);
        Result result = wxUtils.getSqlFromWxPost(bodys,host,path);
        Object data = result.getData();
        String s = data.toString();
        JSONObject jsonObject = JSONObject.parseObject(s);
        Integer modified = Integer.valueOf(jsonObject.getString("deleted"));
        System.out.println(jsonObject.toJSONString());
        System.out.println(modified);
        if (modified!=1){
            throw new TiKuException(20001,"删除失败");
        }
    }

    /**
     * 管理员将原来修订记录里的数据还原的方法
     * @param updateForReviseVo
     */
    @SneakyThrows
    @Override
    public void UpdateForRevise(UpdateForReviseVo updateForReviseVo) {
        String _id = updateForReviseVo.get_id();
        UpdateForRevise updateForRevise = new UpdateForRevise();
        BeanUtils.copyProperties(updateForReviseVo,updateForRevise);
        String jsonString = JSON.toJSONString(updateForRevise);
        //根据question找到题号
        String question = updateForReviseVo.getQuestion();
        Integer tihao = this.findTihao(question);
        Integer index = tihao-1;
        String selectLib = updateForReviseVo.getSelectLib();
        String query = "db.collection(\"shuati\").where({\"name\":\""+selectLib+"\"}).update({data:{[\"title."+index+"\"]:"+jsonString+"}})";
        Result result = this.wxUtils(query);
        JSONObject jsonObject = this.resultToJson(result);
        Integer modified = Integer.valueOf(jsonObject.getString("modified"));
        if (modified==1){
            //删除feedBack
            query = "db.collection(\"feedBack\").where({\"_id\":\""+_id+"\"}).remove()";
            String host = "https://api.weixin.qq.com";
            String path = "/tcb/databasedelete";
            Map<String, String> bodys = new HashMap<>();
            bodys.put("env",env);
            bodys.put("query",query);
            result = wxUtils.getSqlFromWxPost(bodys, host, path);
            jsonObject = this.resultToJson(result);
            System.out.println(jsonString);
            Integer deleted = Integer.valueOf(jsonObject.getString("deleted"));
            if (deleted!=1){
                throw new TiKuException(20001,"feedBack删除错误");
            }
        }
        else {
            throw new TiKuException(20002,"shuati修改错误");
        }
    }

    //添加题库的方法
    @SneakyThrows
    @Override
    public void insert(TiKu tiku) {
        String name = tiku.getName();
        Question question = new Question();
        BeanUtils.copyProperties(tiku,question);
        String questionJson = JSON.toJSONString(question);
        //获取documentId
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databaseupdate";
        String query = "db.collection(\"shuati2\").where({\"name\":\""+name+"\"}).get()";
        HashMap<String, String> bodys = new HashMap<>();
        query = "db.collection(\"shuati\").where({\"name\":\""+name+"\"}).update({data:{\"title\":db.command.push("+questionJson+")}})";
        bodys.put("env",env);
        bodys.put("query",query);
        System.out.println(query.length());
        Result result = wxUtils.getSqlFromWxPost(bodys,host,path);
        JSONObject jsonObject = resultToJson(result);
        System.out.println(jsonObject);
    }

    //得到所有英语听力题目列表
    @SneakyThrows
    @Override
    public Result listeningList(Integer currentPage) {
        int pageSize = 10;
        int skip = pageSize * (currentPage - 1);
        int limit = pageSize;
        String query = "db.collection(\"english_listening\").skip("+skip+").limit("+limit+").get()";
        Result result = wxUtils.getSqlFromWxPost(query);
        return result;
    }

    //保存英语听力题目
    @SneakyThrows
    @Override
    public Result saveListen(EnglishListening englishListening) {
        List<List<ListenQues>> questionList = englishListening.getQuestion();
        List<ListenQues> quesList = new ArrayList<>();
        questionList.forEach(quesList::addAll);
        Map<String, Object> map = new HashMap<>();
        map.put("name",englishListening.getName());
        map.put("src",englishListening.getSrc());
        map.put("type","englishTitle");
        map.put("question",quesList);
        map.put("createTime",System.currentTimeMillis());
        String data = JSON.toJSONString(map);
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databaseadd";
        Map<String, String> bodys = new HashMap<>();
        bodys.put("env",env);
        String query = "db.collection(\"english_listening\").add({data:"+data+"})";
        bodys.put("query",query);
        Result result = wxUtils.getSqlFromWxPost(bodys, host, path);
        return  result;
    }

    @SneakyThrows
    public Result saveListenFromTxt(EnglishListeningForAdd englishListening) {
        String data = JSON.toJSONString(englishListening);
        String host = "https://api.weixin.qq.com";
        String path = "/tcb/databaseadd";
        Map<String, String> bodys = new HashMap<>();
        bodys.put("env",env);
        String query = "db.collection(\"english_listening\").add({data:"+data+"})";
        bodys.put("query",query);
        Result result = wxUtils.getSqlFromWxPost(bodys, host, path);
        return  result;
    }

    //随机出题的方法
    @Override
    public JSONArray random(String subject) {
        //获取对应题库并从中抽题
        JSONArray subjectAndRandom = this.getSubjectAndRandom(subject);
        //后面需要将此题目做成txt或者word
        return subjectAndRandom;
    }



    /**
     * 获取对应题库并从中抽题
     * @param subject
     */
    @SneakyThrows
    public JSONArray getSubjectAndRandom(String subject) {
        //  query = "db.collection(\"shuati\").where({\"name\":\""+name+"\"}).update({data:{\"title\":db.command.push("+questionJson+")}})";
        String query = "db.collection(\"shuati\").where({\"name\":\""+subject+"\"}).get()";
        Result result = wxUtils.getSqlFromWxPost(query);
        JSONObject data = (JSONObject) result.getData();
        JSONArray array = data.getJSONArray("data");
        String String = array.getString(0);
        JSONObject jsonObject = JSONObject.parseObject(String);
        JSONArray title = jsonObject.getJSONArray("title");
        //从中抽题
        int count = 50;
        if ("M1-航空概论".equals(subject)){
            count=30;
        }else if ("M2-航空器维修".equals(subject)) {
            count = 56;
        }else if ("M3-飞机结构和系统".equals(subject)){
            count=178;
        }else if ("M5-航空涡轮发动机".equals(subject)){
            count=85;
        }else if ("M6-航空活塞发动机".equals(subject)){
            count=60;
        }
        JSONArray objects = CommonUtils.randomSelect(title, count);
        return objects;
    }




    private JSONObject resultToJson(Result result){
        Object data = result.getData();
        String s = data.toString();
        JSONObject jsonObject = JSONObject.parseObject(s);
        return jsonObject;
    }

    /**
     * 更新shuati和feedback数据库
     * @param updateQuestion
     * @throws Exception
     */
    @Override
    public void update(UpdateQuestion updateQuestion) throws Exception {


        String selectLib = updateQuestion.getSelectLib();
        //更新shuati2
        Question newQues = updateQuestion.getNewQues();
        String question = newQues.getQuestion();
        String jsonString = JSON.toJSONString(newQues);
        //根据question找到题号
        Integer tihao = this.findTihao(question);
        Integer index = tihao-1;
        String query = "db.collection(\"shuati\").where({\"name\":\""+selectLib+"\"}).update({data:{[\"title."+index+"\"]:"+jsonString+"}})";
        Result result = this.wxUtils(query);
        Object data = result.getData();
        String s = data.toString();
        JSONObject jsonObject = JSONObject.parseObject(s);
        Integer modified = Integer.valueOf(jsonObject.getString("modified"));
        //更新feedBack
        if (modified==1){//如果shuati2修改成功，修改feedBack
            // TODO这里修改feedBack有点问题
            Question oldQues = updateQuestion.getOldQues();
            String question1 = oldQues.getQuestion();
            String answer1 = oldQues.getAnswer();
            String item11 = oldQues.getItem1();
            String item21 = oldQues.getItem2();
            String item31 = oldQues.getItem3();
            String item41 = oldQues.getItem4();
            long time = updateQuestion.getTime();
            String account = updateQuestion.getAccount();
            long now = System.currentTimeMillis();
            query = "db.collection(\"feedBack\").where({\"account\":\""+account+"\",\"time\":"+time+",\"updated\":false}).update({data:{\"reviseTime\":"+now+",\"updated\":true,\"question\":\""+question1+"\",\"item1\":\""+item11+"\",\"item2\":\""+item21+"\",\"item3\":\""+item31+"\",\"item4\":\""+item41+"\",\"answer\":\""+answer1+"\"}})";
            Result feedBackRes = wxUtils(query);
            Object resData = feedBackRes.getData();
            String dataStr = resData.toString();
            JSONObject dataStrJson = JSONObject.parseObject(dataStr);
            Integer feedBackModified = Integer.valueOf(dataStrJson.getString("modified"));
            System.out.println(dataStrJson.toJSONString());
            System.out.println(feedBackModified);
            if (feedBackModified!=1){
                throw new TiKuException(20001,"feedBack修改错误");
            }
        }else {
            throw new TiKuException(20002,"shuati修改错误");
        }
    }

}
